/*
@Language: golang1.21.7
@Author: jackeson
@File: main.go
@Description:
@Time: 2024/7/4
*/

package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"github.com/tarm/serial"
	"io"
	"log"
	"os"
	"strings"
	"time"
)

// 交互式输入
func writeLine(port *serial.Port) {
	scanner := bufio.NewScanner(os.Stdin)
	for {
		fmt.Println(">>>")
		scanner.Scan()
		cmd := scanner.Text()
		if strings.ToLower(cmd) == "exit" {
			break
		}

		_, err := port.Write([]byte(cmd + "\r\n"))
		if err != nil {
			log.Fatalf("failed to write at: %s", err.Error())
		}
	}
}

func readLine(port *serial.Port) {
	reader := bufio.NewReader(port)
	for {
		line, _, err := reader.ReadLine()
		if err != nil {
			if errors.Is(err, io.EOF) {
				fmt.Println("read line is EOF")
				continue
			} else {
				fmt.Printf("read line failed: %s", err.Error())

			}
		}
		fmt.Printf("<<< %s\n", line)
	}
}

func main() {
	// 定义命令行参数
	portPtr := flag.String("p", "/dev/ttyS1", "com")
	baudPtr := flag.Int("b", 115200, "baud")
	flag.Parse()

	// 配置,打开串口
	// 配置串口
	c := &serial.Config{Name: *portPtr, Baud: *baudPtr, ReadTimeout: time.Second * 5}

	// 打开串口
	port, err := serial.OpenPort(c)
	if err != nil {
		log.Fatalf("open serial port failed, com: %s, baud: %d, err:%s", *portPtr, *baudPtr, err.Error())
	}
	defer port.Close()
	fmt.Printf("open serial port success, com: %s, baud: %d\n", *portPtr, *baudPtr)

	go readLine(port)
	writeLine(port)

	fmt.Println("exit!")
}
